import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../models/chat_message_entity.dart';

/// 消息存储服务
/// 
/// 🎯 核心职责：
/// - 本地存储所有聊天消息（三种类型）
/// - 管理未读消息数量（分类统计）
/// - 提供消息查询、清除等操作
/// 
/// 💾 存储结构：
/// - chat_history_{userId}: 某个好友的聊天记录
/// - unread_count_{userId}: 某个好友的未读数（分类）
/// - total_unread: 全局未读数汇总
class MessageStorageService extends GetxService {
  static MessageStorageService get to => Get.find<MessageStorageService>();
  
  final GetStorage _storage = GetStorage();
  
  // 🔥 存储键前缀
  static const String _keyPrefixChatHistory = 'chat_history_';
  static const String _keyPrefixUnreadCount = 'unread_count_';
  static const String _keyTotalUnread = 'total_unread';
  
  // 🔥 响应式未读数统计（全局）
  final Rx<UnreadMessageCount> totalUnreadCount = UnreadMessageCount().obs;
  
  // 🔥 响应式用户未读数映射
  final RxMap<String, UnreadMessageCount> userUnreadCounts = <String, UnreadMessageCount>{}.obs;
  
  // 🔥 消息变化通知（用于触发UI刷新）
  final RxInt messageChangeNotifier = 0.obs;
  
  @override
  Future<void> onInit() async {
    super.onInit();
    debugPrint('🚀 ============= 消息存储服务初始化 =============');
    
    // 加载全局未读数
    await _loadTotalUnreadCount();
    
    debugPrint('✅ 消息存储服务初始化完成');
    debugPrint('📊 全局未读数: ${totalUnreadCount.value}');
  }
  
  // ==================== 消息存储 ====================
  
  /// 保存消息到本地
  Future<void> saveMessage(ChatMessageEntity message) async {
    try {
      final key = _getChatHistoryKey(message.userId);
      final messages = await getMessages(message.userId);
      
      // 🔥 企业级去重逻辑（优化：主要依靠 messageId）
      // 1. 如果有 messageId，只比较 messageId（融云服务器保证唯一性）
      // 2. 如果没有 messageId（临时消息），使用更短的时间阈值（200ms）
      final isDuplicate = messages.any((m) {
        // 如果两条消息都有 messageId，只比较 messageId
        if (m.messageId != null && 
            m.messageId!.isNotEmpty && 
            message.messageId != null && 
            message.messageId!.isNotEmpty) {
          return m.messageId == message.messageId;
        }
        
        // 如果是临时消息（没有 messageId），使用更严格的条件：
        // 相同内容 + 相同发送者 + 时间差小于 200ms（人类不可能这么快）
        return m.content == message.content &&
               m.isMe == message.isMe &&
               (m.timestamp - message.timestamp).abs() < 200;
      });
      
      if (isDuplicate) {
        debugPrint('⚠️ 消息已存在，跳过保存（messageId: ${message.messageId}）');
        return;
      }
      
      // 添加新消息
      messages.add(message);
      
      // 限制历史记录数量（最多200条）
      if (messages.length > 200) {
        messages.removeRange(0, messages.length - 200);
      }
      
      // 保存到本地
      final jsonList = messages.map((m) => m.toJson()).toList();
      await _storage.write(key, jsonList);
      
      debugPrint('💾 消息已保存: ${message.content} (类型: ${message.messageType})');
      
      // 如果是接收的消息，更新未读数
      if (!message.isMe) {
        await _increaseUnreadCount(message.userId, message.messageType);
      }
      
      // 🔥 触发消息变化通知（用于UI刷新）
      messageChangeNotifier.value++;
      debugPrint('🔔 消息变化通知已触发: ${messageChangeNotifier.value}');
      
    } catch (e) {
      debugPrint('💥 保存消息异常: $e');
    }
  }
  
  /// 批量保存消息
  Future<void> saveMessages(List<ChatMessageEntity> messages) async {
    try {
      if (messages.isEmpty) return;
      
      for (final message in messages) {
        await saveMessage(message);
      }
      
      // 注意：单个 saveMessage 已经会触发通知，这里不需要再次触发
      
      debugPrint('💾 批量保存消息完成: ${messages.length}条');
    } catch (e) {
      debugPrint('💥 批量保存消息异常: $e');
    }
  }
  
  /// 获取某个用户的所有消息
  Future<List<ChatMessageEntity>> getMessages(String userId) async {
    try {
      final key = _getChatHistoryKey(userId);
      final jsonList = _storage.read<List>(key);
      
      if (jsonList == null || jsonList.isEmpty) {
        return [];
      }
      
      return jsonList
          .map((json) => ChatMessageEntity.fromJson(Map<String, dynamic>.from(json)))
          .toList();
    } catch (e) {
      debugPrint('💥 获取消息异常: $e');
      return [];
    }
  }
  
  /// 获取某个用户的最后一条消息
  Future<ChatMessageEntity?> getLastMessage(String userId) async {
    try {
      final messages = await getMessages(userId);
      return messages.isNotEmpty ? messages.last : null;
    } catch (e) {
      debugPrint('💥 获取最后一条消息异常: $e');
      return null;
    }
  }
  
  /// 清除某个用户的所有消息
  Future<void> clearMessages(String userId) async {
    try {
      final key = _getChatHistoryKey(userId);
      await _storage.remove(key);
      debugPrint('🗑️ 已清除用户 $userId 的所有消息');
    } catch (e) {
      debugPrint('💥 清除消息异常: $e');
    }
  }
  
  // ==================== 未读数管理 ====================
  
  /// 增加未读数
  Future<void> _increaseUnreadCount(String userId, String messageType) async {
    try {
      final unreadCount = await getUserUnreadCount(userId);
      
      UnreadMessageCount newCount;
      switch (messageType) {
        case 'chat':
          newCount = unreadCount.copyWith(
            chatUnreadCount: unreadCount.chatUnreadCount + 1,
          );
          break;
        case 'friend_request':
          newCount = unreadCount.copyWith(
            friendRequestUnreadCount: unreadCount.friendRequestUnreadCount + 1,
          );
          break;
        case 'activity_request':
          newCount = unreadCount.copyWith(
            activityRequestUnreadCount: unreadCount.activityRequestUnreadCount + 1,
          );
          break;
        default:
          newCount = unreadCount;
      }
      
      // 保存用户未读数
      await _saveUserUnreadCount(userId, newCount);
      
      // 更新全局未读数
      await _updateTotalUnreadCount();
      
      debugPrint('📊 增加未读数: 用户=$userId, 类型=$messageType, 新值=$newCount');
    } catch (e) {
      debugPrint('💥 增加未读数异常: $e');
    }
  }
  
  /// 获取某个用户的未读数
  Future<UnreadMessageCount> getUserUnreadCount(String userId) async {
    try {
      // 优先从内存缓存获取
      if (userUnreadCounts.containsKey(userId)) {
        return userUnreadCounts[userId]!;
      }
      
      // 从本地存储获取
      final key = _getUnreadCountKey(userId);
      final json = _storage.read<Map<String, dynamic>>(key);
      
      if (json == null) {
        return UnreadMessageCount();
      }
      
      final count = UnreadMessageCount.fromJson(json);
      userUnreadCounts[userId] = count;
      return count;
    } catch (e) {
      debugPrint('💥 获取未读数异常: $e');
      return UnreadMessageCount();
    }
  }
  
  /// 清除某个用户的所有未读数
  Future<void> clearUserUnreadCount(String userId) async {
    try {
      final key = _getUnreadCountKey(userId);
      await _storage.remove(key);
      userUnreadCounts.remove(userId);
      
      // 更新全局未读数
      await _updateTotalUnreadCount();
      
      debugPrint('🗑️ 已清除用户 $userId 的所有未读数');
    } catch (e) {
      debugPrint('💥 清除未读数异常: $e');
    }
  }
  
  /// 清除某个用户的某类消息未读数
  Future<void> clearUserUnreadCountByType(String userId, String messageType) async {
    try {
      final unreadCount = await getUserUnreadCount(userId);
      
      UnreadMessageCount newCount;
      switch (messageType) {
        case 'chat':
          newCount = unreadCount.copyWith(chatUnreadCount: 0);
          break;
        case 'friend_request':
          newCount = unreadCount.copyWith(friendRequestUnreadCount: 0);
          break;
        case 'activity_request':
          newCount = unreadCount.copyWith(activityRequestUnreadCount: 0);
          break;
        default:
          return;
      }
      
      await _saveUserUnreadCount(userId, newCount);
      await _updateTotalUnreadCount();
      
      debugPrint('🗑️ 已清除用户 $userId 的 $messageType 未读数');
    } catch (e) {
      debugPrint('💥 清除指定类型未读数异常: $e');
    }
  }
  
  /// 清除所有未读数
  Future<void> clearAllUnreadCount() async {
    try {
      // 清除所有用户的未读数
      for (final userId in userUnreadCounts.keys.toList()) {
        await clearUserUnreadCount(userId);
      }
      
      // 清除全局统计
      totalUnreadCount.value = UnreadMessageCount();
      await _storage.remove(_keyTotalUnread);
      
      debugPrint('🗑️ 已清除所有未读数');
    } catch (e) {
      debugPrint('💥 清除所有未读数异常: $e');
    }
  }
  
  /// 获取全局未读数统计
  Future<UnreadMessageCount> getTotalUnreadCount() async {
    try {
      await _updateTotalUnreadCount();
      return totalUnreadCount.value;
    } catch (e) {
      debugPrint('💥 获取全局未读数异常: $e');
      return UnreadMessageCount();
    }
  }
  
  // ==================== 私有方法 ====================
  
  /// 获取聊天历史存储键
  String _getChatHistoryKey(String userId) {
    return '$_keyPrefixChatHistory$userId';
  }
  
  /// 获取未读数存储键
  String _getUnreadCountKey(String userId) {
    return '$_keyPrefixUnreadCount$userId';
  }
  
  /// 保存用户未读数
  Future<void> _saveUserUnreadCount(String userId, UnreadMessageCount count) async {
    try {
      final key = _getUnreadCountKey(userId);
      await _storage.write(key, count.toJson());
      userUnreadCounts[userId] = count;
    } catch (e) {
      debugPrint('💥 保存用户未读数异常: $e');
    }
  }
  
  /// 加载全局未读数
  Future<void> _loadTotalUnreadCount() async {
    try {
      final json = _storage.read<Map<String, dynamic>>(_keyTotalUnread);
      if (json != null) {
        totalUnreadCount.value = UnreadMessageCount.fromJson(json);
      }
    } catch (e) {
      debugPrint('💥 加载全局未读数异常: $e');
    }
  }
  
  /// 更新全局未读数统计
  Future<void> _updateTotalUnreadCount() async {
    try {
      int totalChat = 0;
      int totalFriend = 0;
      int totalActivity = 0;
      
      // 遍历所有用户的未读数
      for (final userId in userUnreadCounts.keys) {
        final count = userUnreadCounts[userId]!;
        totalChat += count.chatUnreadCount;
        totalFriend += count.friendRequestUnreadCount;
        totalActivity += count.activityRequestUnreadCount;
      }
      
      totalUnreadCount.value = UnreadMessageCount(
        chatUnreadCount: totalChat,
        friendRequestUnreadCount: totalFriend,
        activityRequestUnreadCount: totalActivity,
      );
      
      // 保存到本地
      await _storage.write(_keyTotalUnread, totalUnreadCount.value.toJson());
      
    } catch (e) {
      debugPrint('💥 更新全局未读数异常: $e');
    }
  }
  
  // ==================== 工具方法 ====================
  
  /// 获取所有有消息的用户ID列表
  Future<List<String>> getAllUserIds() async {
    try {
      final keys = _storage.getKeys();
      final userIds = <String>[];
      
      for (final key in keys) {
        if (key is String && key.startsWith(_keyPrefixChatHistory)) {
          final userId = key.replaceFirst(_keyPrefixChatHistory, '');
          userIds.add(userId);
        }
      }
      
      return userIds;
    } catch (e) {
      debugPrint('💥 获取用户ID列表异常: $e');
      return [];
    }
  }
}

